package com.propertypoint.presentation.actions;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import sun.net.www.protocol.http.AuthScheme;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.propertypoint.exception.AuthenticationException;
import com.propertypoint.presentation.model.Agent;
import com.propertypoint.presentation.model.KeyValue;
import com.propertypoint.presentation.model.PieChartData;
import com.propertypoint.service.business.AdvertiesmentServiceImpl;
import com.propertypoint.service.business.AuditServiceImpl;
import com.propertypoint.service.business.UserLoginServiceImpl;
import com.propertypoint.service.general.AdvertiesmentService;
import com.propertypoint.service.general.AuditService;
import com.propertypoint.service.general.UserLoginService;
import com.propertypoint.util.MD5Util;
import com.propertypoint.util.PropertyPointConstants;

/**
 * Servlet implementation class UserLoginServlet
 */
@WebServlet("/UserLoginServlet")
public class UserLoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UserLoginService userLoginService = new UserLoginServiceImpl();
	private AuditService auditService=new AuditServiceImpl();
	
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UserLoginServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(
				request.getInputStream()));
		String json = "";
		if (br != null) {
			json = br.readLine();

		}

		JsonParser paser = new JsonParser();
		JsonElement element = paser.parse(json);
		JsonObject jsonObject = element.getAsJsonObject();
		JsonElement elementUsername = jsonObject
				.get(PropertyPointConstants.USERNAME);
		JsonElement elementPassword = jsonObject
				.get(PropertyPointConstants.PASSWORD);
		String username = elementUsername.getAsString();
		String password = elementPassword.getAsString();
		HttpSession session = request.getSession();
		 
		PrintWriter out = response.getWriter();
		response.setContentType("text/html");
		response.setHeader("Cache-control", "no-cache, no-store");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Expires", "-1");

		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "POST");
		response.setHeader("Access-Control-Allow-Headers", "Content-Type");
		response.setHeader("Access-Control-Max-Age", "86400");

		JsonObject authObject = new JsonObject();
		try {

			Agent agent = (Agent) userLoginService.authenticateUser(username,
					MD5Util.getMD5String(password));
			session.setAttribute("user", agent);
			
			session.setAttribute("login_status", "true");
			
			List<KeyValue> pieDataList =auditService.getSearchHitsHDBLocation();
			session.setAttribute("pieDataListHDBHits", pieDataList);
			authObject.addProperty("success", true);
			out.println(authObject.toString());
			out.close();
		} catch (AuthenticationException e) {
			session.setAttribute("login_status", "false");
			request.setAttribute("login_error", e.getMessage());
			authObject.addProperty("success", false);
			authObject.addProperty("auth_error_message", e.getMessage());
			out.println(authObject.toString());
			out.close();
		} catch (Exception e) {
			session.setAttribute("login_status", "false");
			request.setAttribute("login_error",
					"Unknown Error,please contact our system admin");
			e.printStackTrace();
			authObject.addProperty("success", false);
			authObject.addProperty("auth_error_message", e.getMessage());
			out.println(authObject.toString());
			out.close();
			 
		}

	}

}
